import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

// 全局筛选状态管理 store
export const useFilterStore = defineStore('filter', () => {
  // 存储每个页面的筛选配置
  const filterConfigs = reactive({})
  // 存储每个页面的当前筛选值
  const filterValues = reactive({})
  // 当前页面 key
  const currentPage = ref(null)

  // 注册筛选配置
  function registerFilterConfig(pageKey, config) {
    filterConfigs[pageKey] = config
    if (!filterValues[pageKey]) {
      filterValues[pageKey] = {}
    }
  }

  // 设置当前页面
  function setCurrentPage(pageKey) {
    currentPage.value = pageKey
  }

  // 获取当前页面的筛选值
  const getCurrentValues = computed(() => {
    if (!currentPage.value) return {}
    return filterValues[currentPage.value] || {}
  })

  // 更新筛选值
  function updateFilterValues(pageKey, values) {
    filterValues[pageKey] = { ...values }
  }

  // 清空当前页面筛选值
  function clearFilterValues(pageKey) {
    filterValues[pageKey] = {}
  }

  // 清空单个筛选项
  function clearSingleFilter(pageKey, key) {
    if (filterValues[pageKey]) {
      delete filterValues[pageKey][key]
    }
  }

  // 注销页面
  function unregisterPage(pageKey) {
    delete filterConfigs[pageKey]
    delete filterValues[pageKey]
    if (currentPage.value === pageKey) {
      currentPage.value = null
    }
  }

  // 是否有激活的筛选项
  const hasActiveFilters = computed(() => {
    const values = getCurrentValues.value
    return Object.values(values).some(v => v !== null && v !== undefined && v !== '' && !(Array.isArray(v) && v.length === 0))
  })

  // 激活筛选项数量
  const activeFilterCount = computed(() => {
    const values = getCurrentValues.value
    return Object.values(values).filter(v => v !== null && v !== undefined && v !== '' && !(Array.isArray(v) && v.length === 0)).length
  })

  // 生成筛选标签
  function generateFilterTags(pageKey) {
    const config = filterConfigs[pageKey]
    const values = filterValues[pageKey] || {}
    if (!config || !config.sections) return []
    const tags = []
    config.sections.forEach(section => {
      if (section.fields) {
        section.fields.forEach(field => {
          const value = values[field.key]
          if (value !== null && value !== undefined && value !== '' && !(Array.isArray(value) && value.length === 0)) {
            tags.push({
              key: field.key,
              label: field.label || field.key,
              value
            })
          }
        })
      }
    })
    return tags
  }

  return {
    filterConfigs,
    filterValues,
    currentPage,
    registerFilterConfig,
    setCurrentPage,
    getCurrentValues,
    updateFilterValues,
    clearFilterValues,
    clearSingleFilter,
    unregisterPage,
    hasActiveFilters,
    activeFilterCount,
    generateFilterTags
  }
}) 